package com.xaicode.learn.netty.codec2;

import cn.hutool.core.util.RandomUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/13 0013 23:47
 */
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    // on connect active
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        // send Student or Worker
        /*
            0 student
            1 worker
         */
        int random = RandomUtil.randomInt(0, 2);
        Codec2Proto.All sendObj = null;

        if (random == 0) {
            sendObj = Codec2Proto.All.newBuilder()
                    .setDataType(Codec2Proto.All.DateType.StudentType)
                    .setStudent(Codec2Proto.Student
                            .newBuilder()
                            .setId(1)
                            .setName(RandomUtil.randomString(6))
                            .build())
                    .build();
        } else {
            sendObj = Codec2Proto.All.newBuilder()
                    .setDataType(Codec2Proto.All.DateType.WorkerType)
                    .setWorker(Codec2Proto.Worker
                            .newBuilder()
                            .setName(RandomUtil.randomString(6))
                            .setAge(RandomUtil.randomInt(20, 99))
                            .build())
                    .build();
        }

        ctx.writeAndFlush(sendObj);
    }

    // read
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        log.info("ctx: {}", ctx);

        // msg to netty byte buffer
        ByteBuf byteBuf = (ByteBuf) msg;
        log.info("read server [{}] msg: {}", ctx.channel().remoteAddress(), byteBuf.toString(CharsetUtil.UTF_8));
    }

    // on exception
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
